package top.guxx.mall.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import top.guxx.mall.MallException;
import top.guxx.mall.Response;
import top.guxx.mall.config.RedisService;
import top.guxx.mall.constants.Constants;
import top.guxx.mall.domain.dto.CreatePayReqDTO;
import top.guxx.mall.domain.req.ShopCartReq;
import top.guxx.mall.domain.res.PayOrderRes;
import top.guxx.mall.service.IOrderService;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Author：Guxx
 * @Description：
 * @Date：2025/2/22 20:45
 * @Filename：AliPayController
 */

@Slf4j
@RestController
@CrossOrigin("*")
@RequestMapping("/api/v1/alipay/")
public class AliPayController {

    @Value("${alipay.alipay_public_key}")
    private String alipayPublicKey;

    @Resource
    private IOrderService orderService;

    @Resource
    private RedisService redisService;


    /**
     * http://localhost:8091/api/v1/alipay/create_pay_order?userId=1001&productId=100001
     */
    @RequestMapping(value = "create_pay_order", method = RequestMethod.POST)
    public Response<String> createOrder(@RequestBody CreatePayReqDTO createPayReqDTO){
        try {
            log.info("商品下单，根据商品ID创建支付单开始 userId:{} productId:{}", createPayReqDTO.getUserId(), createPayReqDTO.getUserId());
            String userId = createPayReqDTO.getUserId();
            Map<String, String> productCountMap = createPayReqDTO.getProductCountMap();
            PayOrderRes payOrderRes = orderService.createOrder(ShopCartReq.builder().productCountMap(productCountMap).userId(userId).build());

            log.info("商品下单，根据商品ID创建支付单成功 userId:{} productId:{}", createPayReqDTO.getUserId(), createPayReqDTO.getUserId());

            //发入延迟队列异步扣减库存
            Map<String, String> map = createPayReqDTO.getProductCountMap();
            for (String key : map.keySet()) {
                redisService.addTaskToQueue(new HashMap<String, Integer>(){{
                    put(key,Integer.parseInt(map.get(key)));
                }}.toString(),60);
            }

            return Response.<String>builder()
                    .code(Constants.ResponseCode.SUCCESS.getCode())
                    .info(Constants.ResponseCode.SUCCESS.getInfo())
                    .data(payOrderRes.getPayUrl())
                    .build();

        }catch (Exception e){
            log.error("商品下单，根据商品ID创建支付单失败 userId:{} productId:{}", createPayReqDTO.getUserId(), createPayReqDTO.getUserId(), e);
            return Response.<String>builder()
                    .code(Constants.ResponseCode.UN_ERROR.getCode())
                    .info(Constants.ResponseCode.UN_ERROR.getInfo())
                    .build();

        }
    }

    /**
     * http://www.guxx.top:7003/api/v1/alipay/alipay_notify_url
     */
    @RequestMapping(value = "alipay_notify_url", method = RequestMethod.POST)
    public String payNotify(HttpServletRequest request){
        log.info("支付回调，消息接收 {}", request.getParameter("trade_status"));

        try {
            if (!request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
                return "false";
            }

            Map<String, String> params = new HashMap<>();
            Map<String, String[]> requestParams = request.getParameterMap();
            for (String name : requestParams.keySet()) {
                params.put(name, request.getParameter(name));
            }

            String tradeNo = params.get("out_trade_no");
            /*String gmtPayment = params.get("gmt_payment");
            String alipayTradeNo = params.get("trade_no");*/
            String sign = params.get("sign");
            String content = AlipaySignature.getSignCheckContentV1(params);
            // 验证签名
            boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, alipayPublicKey, "UTF-8");
            // 支付宝验签
            if (!checkSignature) {
                return "false";
            }

            // 验签通过
            log.info("支付回调，交易名称: {}", params.get("subject"));
            log.info("支付回调，交易状态: {}", params.get("trade_status"));
            log.info("支付回调，支付宝交易凭证号: {}", params.get("trade_no"));
            log.info("支付回调，商户订单号: {}", params.get("out_trade_no"));
            log.info("支付回调，交易金额: {}", params.get("total_amount"));
            log.info("支付回调，买家在支付宝唯一id: {}", params.get("buyer_id"));
            log.info("支付回调，买家付款时间: {}", params.get("gmt_payment"));
            log.info("支付回调，买家付款金额: {}", params.get("buyer_pay_amount"));
            log.info("支付回调，支付回调，更新订单 {}", tradeNo);


            // 可以增加 code 10000 与 tradeStatus TRADE_SUCCESS 判断
            orderService.changeOrderPaySuccess(tradeNo);

            return "success";
        }catch (Exception e) {
            log.error("支付回调，处理失败", e);
            return "false";
        }
    }

}

